package com.itheima.service.impl;

import com.itheima.common.utils.SMSUtils;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据预约id查询预约信息
     */
    @Override
    public Order findById(Integer id) {
        return orderMapper.findById(id);
    }
    /**
     * 体检预约
     */
    @Override
    public Integer submitOrder(Order order) {
        //验证码
        String code = generateCode();
        log.info("验证码为：{}", code);
        //调用方法发送验证码
        SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE,order.getTelephone(),code);
        //存储code和电话
        redisTemplate.opsForValue().set(code, order.getTelephone(),5, TimeUnit.MINUTES);
        //验证是否正确
        if(validateCode(order.getValidateCode(), order.getTelephone()) == false){
            return -1;
        }
        //操作member表，查询是否有此人
        Member member = memberMapper.selectByIdCard(order.getIdCard());
        if (member == null){
            //没有此人就插入此人并拿到memberID
            Integer member_id = memberMapper.addmember(order).getId();
            //再插入order表
            order.setOrderStatus("未到诊");
            order.setMemberId(member_id);
            Integer id = orderMapper.add(order).getId();
            return id;
        }
        //有此人就拿到memberId
        Integer member_id = member.getId();
        //再插入order表
        order.setOrderStatus("未到诊");
        order.setMemberId(member_id);
        Integer id = orderMapper.add(order).getId();
        return id;
    }
    /**
     * 生成验证码
     * @param
     * @return 生成的验证码
     */
    private static String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
    /**
     * 验证验证码和电话号码
     * @param code 用户输入的验证码
     * @param phoneNumber 用户输入的电话号码
     * @return 验证结果
     */
    public boolean validateCode(String code, String phoneNumber) {
        String storedPhoneNumber = (String) redisTemplate.opsForValue().get(code);
        if (storedPhoneNumber == null) {
            return false;
        }
        return storedPhoneNumber.equals(phoneNumber);
    }
}
